#include "registerwindow.h"
#include "ui_registerwindow.h"
#include "utils/deviceutils.h"
#include "utils/md5.h"
#include "setting.h"
#include "QDebug"
#include <QMessageBox>
#include "httpclient.h"
#include "bean/loginbean.h"
#include "utils/gamemanager.h"
#include "tlbbcode.h"

RegisterWindow::RegisterWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RegisterWindow)
{
    ui->setupUi(this);
    leRegisterCode = ui->le_registerCode;
    initData();
}

void RegisterWindow::initData()
{
    leRegisterCode->setText(Setting::getInstance()->getRegisterCode());
    checkRegisterCode(Setting::getInstance()->getRegisterCode());
}

void RegisterWindow::goMainWindow()
{
    mainWindow= new MainWindow();
    mainWindow->show();
    close();
}

RegisterWindow::~RegisterWindow()
{
    delete ui;
}


void RegisterWindow::on_registerBtn_clicked()
{
    QString registerCode = leRegisterCode->text();
    if(registerCode.isEmpty()){
        QMessageBox::warning(this,"系统提示", "请输入正确的卡密",QMessageBox::Ok);
        return;
    }

    checkRegisterCode(registerCode);
}

void RegisterWindow::checkRegisterCode(QString registerCode)
{
    if(registerCode.isNull() || registerCode.isEmpty()){
        return;
    }
    HttpClient(LOGIN).success([=](const QString &response) {
        qDebug() << response;
        LoginBean loginBean;
        LoginBean::jsonToObject(response.toUtf8(),loginBean);
        if(loginBean.data.version > VERSION_CODE){
            QMessageBox::warning(this,"系统提示", QString("当前版本为V%1，有新的软件版本V%2,请联系售后").arg(VERSION_CODE).arg(loginBean.data.version),QMessageBox::Ok);
            return;
        }
        Setting::getInstance()->setRegisterCode(registerCode);
        netCallBack(loginBean);
    }).param("authCode", registerCode)
            .param("time",QString::number(QDateTime::currentMSecsSinceEpoch()))
            .post();

}


void RegisterWindow::netCallBack(LoginBean loginBean)
{
    if(loginBean.code == SUCCESS){

        GameManager::getInstantce()->invalidTime = loginBean.data.invalidTime;
        GameManager::getInstantce()->token = loginBean.data.token;

        goMainWindow();
    }else if(loginBean.code == TOKEN_INVALID){
        QMessageBox::warning(this,"系统提示", "卡密不存在或已失效",QMessageBox::Ok);
    }
}
